package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.model.result.UserBindCardsResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.ui.dialog.LoadingDialog;
import com.cardbaobao.cardbabyclient.utils.ApkUtil;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.PhoneInfoUtil;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;

/**
 * 设置
 * Created by zad
 * 2016/12/26 20:43
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.update_pass_layout)
    LinearLayout update_pass_layout;//修改密码
    @BindView(R.id.feedback_layout)
    LinearLayout feedback_layout;//意见反馈
    @BindView(R.id.uodate_version_layout)
    LinearLayout update_version_layout;//版本更新
    @BindView(R.id.about_layout)
    LinearLayout about_layout;//关于我们
    @BindView(R.id.app_evaluation_layout)
    LinearLayout appEvaluationLayout;//我要评分
    @BindView(R.id.login_out)
    TextView login_out;
    @BindView(R.id.ll_personal_info)
    LinearLayout ll_personal_info;
    @BindView(R.id.rl_update_repay_pwd)
    RelativeLayout rl_update_repay_pwd;
    /**
     * 版本检测dialog
     */
    private LoadingDialog updateVersionDialog;

    private List<UserBindCards.DebitCard> debitCards;

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_setting_page;

        debitCards = new ArrayList<>();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        update_pass_layout.setOnClickListener(this);
        feedback_layout.setOnClickListener(this);
        about_layout.setOnClickListener(this);
        appEvaluationLayout.setOnClickListener(this);
        login_out.setOnClickListener(this);
        ll_personal_info.setOnClickListener(this);
        rl_update_repay_pwd.setOnClickListener(this);

        initLoginView();
        //判断当前版本号是否是最新版本号
        int serviceCode = SharedPreferencesUtil.CbbInfo.getAppLatestVersionCode();
        if (PhoneInfoUtil.getVersion(mContext) < serviceCode) {
            //手机当前版本号小于服务器版本号，提示有新版本需要更新
            update_version_layout.setOnClickListener(this);
            TextView tv_version = (TextView) findViewById(R.id.id_tv_version_tip);
            tv_version.setText("有新版本更新");
        }

        loadData();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x023));
        GoogleAnalyticsUtil.setScreenName(Google.SETTING);
    }

    private void initLoginView() {
        if (mApplication.getIsLogin()) {
            update_pass_layout.setVisibility(View.VISIBLE);
            login_out.setVisibility(View.VISIBLE);
        } else {
            update_pass_layout.setVisibility(View.GONE);
            login_out.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent=new Intent();
        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
        switch (view.getId()) {
            case R.id.ll_personal_info://个人信息
                SelfUtils.buriedClickData(Self.Action.app_click_setting_personal_info,
                        Self.Action.app_click_setting_personal_info_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                intent.setClass(mContext,AvatarNickNameActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.update_pass_layout:
                //修改密码
                SelfUtils.buriedClickData(Self.Action.app_click_setting_modify_login_pwd,
                        Self.Action.app_click_setting_modify_login_pwd_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                intent.setClass(mContext,UpdatePasswordActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.feedback_layout:
                //意见反馈
                mContext.startActivity(new Intent(mContext, FeedbackActivity.class));
                break;
            case R.id.uodate_version_layout:
                //版本更新
                if (updateVersionDialog == null) {
                    updateVersionDialog = new LoadingDialog(mContext);
                    updateVersionDialog.setShowText("请求中...");
                }
                updateVersionDialog.show();
                ApkUtil.updateVersion(mContext, true, updateVersionDialog);

                break;
            case R.id.about_layout:
                //关于我们
                UmengEventUtils.pageEvent(mContext,
                        ApplicationHelper.getApplicationContext().getString(R.string.event_0x026));
                initIntent();
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra("title", "关于我们");
                mIntent.putExtra("webUrl", URLUtil.ABOUT_US);
                mContext.startActivity(mIntent);
                break;
            case R.id.app_evaluation_layout:
                //我要评分
                UmengEventUtils.pageEvent(mContext,
                        ApplicationHelper.getApplicationContext().getString(R.string.event_0x027));
                initIntent();
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setData(Uri.parse("market://details?id=" + getPackageName()));
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (getPackageManager().resolveActivity(mIntent,
                        PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    mContext.startActivity(mIntent);
                } else {
                    ToastUtil.showToast("您尚未安装应用市场，请下载后再试");
                }
                break;
            case R.id.login_out:
                //退出登陆
                SelfUtils.buriedClickData(Self.Action.app_click_login_out,
                        Self.Action.app_click_login_out_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mApplication.clearUser();
                //重新显示页面ui
                initLoginView();
                new BroadcastController(mContext).notifyUserLogin();
                finish();
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_EXIT);
                break;
            case R.id.rl_update_repay_pwd:
                if (debitCards != null && debitCards.size() > 0) {//已绑卡
                    SelfUtils.buriedClickData(Self.Action.app_click_setting_modify_payment_pwd,
                            Self.Action.app_click_setting_modify_payment_pwd_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    toRepaymenPwdView(this, 1);
                }
                break;
        }
    }

    /**
     * 去 设置或修改支付密码
     *
     * @param mContext
     * @param value
     */
    private void toRepaymenPwdView(Context mContext, int value) {
        Intent intent = new Intent();
        intent.setClass(mContext, RepaymentPwdOneActivity.class);
        intent.putExtra("type", value);
        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
        startActivity(intent);
    }

    /**
     * 获取储蓄卡
     */
    public void loadData() {
        showProgressDialog(false);
        Api.getUserBindCards(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        UserBindCardsResult result = JsonUtil.json2Object(s, UserBindCardsResult.class);
                        if (result.getCode() == Constant.SUC_CODE) {
                            UserBindCards cards = result.getData();
                            if (cards != null) {
                                debitCards.clear();
                                //储蓄卡
                                debitCards.addAll(cards.getDebitCardList());
                                if (debitCards != null && debitCards.size() > 0) {//已绑卡
                                    rl_update_repay_pwd.setVisibility(View.VISIBLE);
                                }
                            }
                        } else {
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

}
